/**
 * 商品缓存管理工具
 * 提供统一的商品数据缓存机制，支持10分钟有效期
 * 支持多租户org_id隔离
 */

import { API_CONFIG } from '@/api/config.js'

const CACHE_DURATION = 10 * 60 * 1000 // 10分钟的毫秒数
const GLOBAL_CACHE_KEY = 'global_products_cache'

export default {
  /**
   * 检查缓存是否有效
   * @param {string} cacheKey 缓存键
   * @returns {boolean} 是否有效
   */
  isCacheValid(cacheKey) {
    const cacheData = uni.getStorageSync(cacheKey)
    if (!cacheData || !cacheData.timestamp) {
      return false
    }
    const now = Date.now()
    const cacheTime = cacheData.timestamp
    return (now - cacheTime) < CACHE_DURATION
  },

  /**
   * 获取缓存数据
   * @param {string} cacheKey 缓存键
   * @returns {any} 缓存的数据
   */
  getCacheData(cacheKey) {
    const cacheData = uni.getStorageSync(cacheKey)
    return cacheData ? cacheData.data : null
  },

  /**
   * 设置缓存数据
   * @param {string} cacheKey 缓存键
   * @param {any} data 要缓存的数据
   */
  setCacheData(cacheKey, data) {
    const cacheData = {
      data: data,
      timestamp: Date.now()
    }
    uni.setStorageSync(cacheKey, cacheData)
    console.log(`缓存数据已保存: ${cacheKey}, 有效期至: ${new Date(Date.now() + CACHE_DURATION).toLocaleString()}`)
  },

  /**
   * 获取商品缓存
   * @param {string} type 商品类型 (hot, recommend, new, all)
   * @param {string} orgId 组织ID，用于多租户隔离
   * @returns {array|null} 商品数据数组或null
   */
  getProductCache(type, orgId = API_CONFIG.ORG_ID) {
    const cacheKey = orgId ? `products_${type}_org_${orgId}` : `products_${type}`
    if (this.isCacheValid(cacheKey)) {
      console.log(`使用缓存的${type}商品数据 (org_id: ${orgId || 'default'})`)
      return this.getCacheData(cacheKey)
    }
    return null
  },

  /**
   * 设置商品缓存
   * @param {string} type 商品类型 (hot, recommend, new, all)
   * @param {array} data 商品数据数组
   * @param {string} orgId 组织ID，用于多租户隔离
   */
  setProductCache(type, data, orgId = API_CONFIG.ORG_ID) {
    const cacheKey = orgId ? `products_${type}_org_${orgId}` : `products_${type}`
    this.setCacheData(cacheKey, data)
    
    // 同时更新全局商品缓存，供其他页面使用
    const globalCacheKey = orgId ? `${GLOBAL_CACHE_KEY}_org_${orgId}` : GLOBAL_CACHE_KEY
    let globalCache = this.getCacheData(globalCacheKey) || {}
    globalCache[type] = {
      data: data,
      timestamp: Date.now()
    }
    this.setCacheData(globalCacheKey, globalCache)
  },

  /**
   * 从全局缓存获取商品数据
   * @param {string} type 商品类型
   * @param {string} orgId 组织ID，用于多租户隔离
   * @returns {array|null} 商品数据数组或null
   */
  getGlobalProductCache(type, orgId = API_CONFIG.ORG_ID) {
    const globalCacheKey = orgId ? `${GLOBAL_CACHE_KEY}_org_${orgId}` : GLOBAL_CACHE_KEY
    const globalCache = this.getCacheData(globalCacheKey)
    if (globalCache && globalCache[type]) {
      const typeCache = globalCache[type]
      const now = Date.now()
      if ((now - typeCache.timestamp) < CACHE_DURATION) {
        console.log(`从全局缓存获取${type}商品数据 (org_id: ${orgId || 'default'})`)
        return typeCache.data
      }
    }
    return null
  },

  /**
   * 清除指定类型的商品缓存
   * @param {string} type 商品类型
   * @param {string} orgId 组织ID，用于多租户隔离
   */
  clearProductCache(type, orgId = API_CONFIG.ORG_ID) {
    const cacheKey = orgId ? `products_${type}_org_${orgId}` : `products_${type}`
    uni.removeStorageSync(cacheKey)
    
    // 同时清除全局缓存中的对应数据
    const globalCacheKey = orgId ? `${GLOBAL_CACHE_KEY}_org_${orgId}` : GLOBAL_CACHE_KEY
    let globalCache = this.getCacheData(globalCacheKey) || {}
    if (globalCache[type]) {
      delete globalCache[type]
      this.setCacheData(globalCacheKey, globalCache)
    }
    console.log(`已清除${type}商品缓存 (org_id: ${orgId || 'default'})`)
  },

  /**
   * 清除所有商品缓存
   * @param {string} orgId 组织ID，用于多租户隔离
   */
  clearAllProductCache(orgId = API_CONFIG.ORG_ID) {
    const types = ['hot', 'recommend', 'new', 'all']
    types.forEach(type => {
      const cacheKey = orgId ? `products_${type}_org_${orgId}` : `products_${type}`
      uni.removeStorageSync(cacheKey)
    })
    const globalCacheKey = orgId ? `${GLOBAL_CACHE_KEY}_org_${orgId}` : GLOBAL_CACHE_KEY
    uni.removeStorageSync(globalCacheKey)
    console.log(`已清除所有商品缓存 (org_id: ${orgId || 'default'})`)
  },

  /**
   * 获取缓存状态信息
   * @param {string} orgId 组织ID，用于多租户隔离
   * @returns {object} 缓存状态
   */
  getCacheStatus(orgId = API_CONFIG.ORG_ID) {
    const types = ['hot', 'recommend', 'new', 'all']
    const status = {}
    
    types.forEach(type => {
      const cacheKey = orgId ? `products_${type}_org_${orgId}` : `products_${type}`
      const isValid = this.isCacheValid(cacheKey)
      const data = this.getCacheData(cacheKey)
      status[type] = {
        valid: isValid,
        count: data ? data.length : 0,
        timestamp: data ? new Date(uni.getStorageSync(cacheKey).timestamp).toLocaleString() : null
      }
    })
    
    return status
  }
}